import type { ReactElement } from 'react';
import { useParams } from 'react-router-dom-v5-compat';

import useIntegrations from './hooks/useIntegrations';

import IntegrationPage from './IntegrationPage';
import IntegrationForm from './IntegrationForm';
import IntegrationsNotFoundPage from './IntegrationsNotFoundPage';
import { getIsMachineAccessConfig } from './utils/integrationUtils';
import type { IntegrationSource, IntegrationType } from './utils/integrationUtils';

export type EditIntegrationPageProps = {
    source: IntegrationSource;
    type: IntegrationType;
};

function EditIntegrationPage({ source, type }: EditIntegrationPageProps): ReactElement {
    const { id } = useParams();
    const integrations = useIntegrations({ source, type });
    const integration = integrations.find((datum) => datum.id === id);

    if (!integration) {
        return <IntegrationsNotFoundPage />;
    }

    return (
        <IntegrationPage
            title={
                getIsMachineAccessConfig(source, type) ? 'Manage configuration' : 'Edit integration'
            }
            name={integration.name}
        >
            <IntegrationForm source={source} type={type} initialValues={integration} isEditable />
        </IntegrationPage>
    );
}

export default EditIntegrationPage;
